package application;

import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.TimeUnit;

import jeopardy.common.protocol.game.play.AnswerMsg;
import jeopardy.common.protocol.game.play.CurrentUsersMsg;
import jeopardy.common.protocol.game.play.GameRecordMsg;
import jeopardy.common.protocol.game.play.NewQuestionMsg;
import jeopardy.common.protocol.game.play.NotifyStartMsg;
import jeopardy.common.protocol.game.play.QnAAttemptedMsg;
import jeopardy.common.protocol.game.play.QuestionAnswerMsg;

public class GameScreenLogic {
	
	private Socket sock;
	private GameScreenController gsc;
	private BlockingQueue<AnswerMsg> answers;
	boolean isDone = false;
	
	GameScreenLogic(Socket s, GameScreenController g, BlockingQueue<AnswerMsg> a){
		this.sock = s;
		this.gsc = g;
		this.answers = a;
		
		Thread reader = new Thread(new Runnable(){
			@Override
			public void run(){
				try{
					ObjectInputStream ois = new ObjectInputStream(sock.getInputStream());
					
					while(!isDone){
						Object readObj = ois.readObject();
						
						if(readObj instanceof NotifyStartMsg){
							NotifyStartMsg msg = (NotifyStartMsg) readObj;
							gsc.notifyStart(msg.getStartsInMilli(), msg.getPlayers());
						}else if(readObj instanceof NewQuestionMsg){
							NewQuestionMsg msg = (NewQuestionMsg) readObj;
							gsc.setUsers(msg.getEligiblePlayers());
							gsc.newQuestion(msg.getQuestion(), msg.getPoints(), msg.getTimeToPlayMillis());
						}else if(readObj instanceof CurrentUsersMsg){
							CurrentUsersMsg msg = (CurrentUsersMsg) readObj;
							gsc.setUsers(msg.getPlayers());
						}else if(readObj instanceof QnAAttemptedMsg){
							QnAAttemptedMsg msg = (QnAAttemptedMsg) readObj;
							gsc.questionAttempted(msg.getAnswer(), msg.getAnswerer(), msg.getTimeTookMilliseconds());
							gsc.setUsers(msg.getEligiblePlayers());
						}else if(readObj instanceof QuestionAnswerMsg){
							QuestionAnswerMsg msg = (QuestionAnswerMsg) readObj;
							gsc.questionAnswered(msg.getAnswer(), msg.getWinner(), msg.getPoints(), msg.getTimeMillis());
						}else if(readObj instanceof GameRecordMsg){
							GameRecordMsg msg = (GameRecordMsg) readObj;
							gsc.gameFinished(msg.getWinner(), msg.getPointsWon());
							isDone = true;
						}else{
							//TODO uknown class?
						}
					}
					ois.close();
				}catch(Exception e){
					
				}
			}
		});
		reader.start();
		
		Thread writer = new Thread(new Runnable(){
			@Override
			public void run(){
				try{
					ObjectOutputStream oos = new ObjectOutputStream(sock.getOutputStream());
					
					while(!isDone){
						AnswerMsg nextAnswer = answers.poll(1, TimeUnit.SECONDS);
						oos.writeObject(nextAnswer);
						oos.flush();
					}
					
					oos.close();
				}catch(Exception e){
					try{
					
					}catch(Exception ee){} //TODO log?
				}
			}
		});
		writer.start();
	}
}
